Functions


Functions are one of the fundamental building blocks in JavaScript. A function is a reusable block of code designed to perform a particular task.

1. Function Declaration

A function declaration defines a function with the specified parameters.

function functionName(parameter) {
    ---code--- 
    return value;
}
functionName(x); //function call

2. Function Expression

A function expression defines a function inside an expression, and can be anonymous.

const greet = function(name) {
    return "Hello, " + name + "!";
};
console.log(greet("Bob")); // Outputs: Hello, Bob!

3. Arrow Functions

Arrow functions provide a shorter syntax for writing functions.

const greet = (name) => {
    return "Hello, " + name + "!";
};
console.log(greet("Charlie")); // Outputs: Hello, Charlie!

4. Function Parameters and Arguments

Functions can take parameters and be called with arguments.

function add(a, b) {
    return a + b;
}
//or 
// const add = (a,b)=>(a+b) 
console.log(add(2, 3)); // Outputs: 5

5. Default Parameters

Default parameters allow named parameters to be initialized with default values if no value or undefined is passed.

function greet(name = "Guest") {
    return "Hello, " + name + "!";
}
console.log(greet()); // Outputs: Hello, Guest!

6. Rest Parameters

Rest parameters allow a function to accept an indefinite number of arguments as an array.

function sum(...numbers) {
    return numbers.reduce((acc, curr) => acc + curr, 0);
}
console.log(sum(1, 2, 3, 4)); // Outputs: 10

7. Anonymous Functions

Anonymous functions are functions without a name, often used as arguments to other functions.

setTimeout(function() {
    console.log("This is an anonymous function.");
}, 1000);

8. Immediately Invoked Function Expressions (IIFE)

An IIFE is a function that runs as soon as it is defined.

(function() {
    console.log("This is an IIFE.");
})();